<?php

	include('dbchatcon.php');
	
	if ($_REQUEST['to_id'] != '-1')
	{
		// Check if there is a chatTable already created.
		$result = mysql_query("SELECT * FROM chatsRemaining WHERE (from_id = '".$_REQUEST['user_id']."' AND to_id = '".$_REQUEST['to_id']."') OR
		(from_id = '".$_REQUEST['to_id']."' AND to_id = '".$_REQUEST['user_id']."') LIMIT 1");
		
		if (mysql_num_rows($result) > 0) // The table is aldready created
		{
			echo mysql_result($result, 0, 'c_id');
		} else {
			
			// Save the call to chat in the chatsRemaining table.
			mysql_query("INSERT INTO chatsRemaining (to_id, from_id, date_created, seen) VALUES ('".$_REQUEST['to_id']."', '".$_REQUEST['user_id']."', '".strtotime(date("Y-m-d H:i:s"))."', '0')");
			
			// Get the id of that chat to create the chat table.
			$result = mysql_query("SELECT * FROM chatsRemaining WHERE from_id = '".$_REQUEST['user_id']."' ORDER BY date_created DESC LIMIT 1");
			
			$chatTableName = mysql_result($result, 0, 'c_id');
			
			mysql_query("CREATE TABLE chatN_".$chatTableName." (
						text_id int(11) NOT NULL auto_increment,
						author_id int(11) NOT NULL,
						text_content varchar(255) NOT NULL,
						date_created int(11) NOT NULL,
						PRIMARY KEY (text_id)
						)");
			
			echo $chatTableName;
		}
	} else {
		$result = mysql_query("SELECT * FROM chatsRemaining WHERE to_id = '".$_REQUEST['user_id']."' AND seen = 0");
		
		while ($row = mysql_fetch_array($result)) 
		{
			mysql_query("REPLACE INTO chatsRemaining (c_id, to_id, from_id, date_created, seen) VALUES ('".$row['c_id']."', '".$row['to_id']."', '".$row['from_id']."', '".$row['date_created']."', '1')");			
			echo $row['c_id'];
			break;		// FALTA HACER ALGO CUANDO MAS DE UNA PERSONA QUIERE HABLARTE.
		}
	}
?>